<template>
  <div class="page_seekJob">
    <!-- <van-nav-bar :title="`找${jobCategoryObj[jobTypeId]}`"
            left-arrow
    @click-left="$router.push('/')" />-->

    <van-row class="title_home" type="flex" justify="space-between" align="center">
      <van-col span="2" class="city_home" @click="$router.push('/myCompany/')">
        <van-icon name="arrow-left" class="icon" color="#1989fa" />
      </van-col>

      <van-col span="4" v-if="!getJobListtype" class="city_home" @click="toAddressPage">
        <van-icon name="location-o" class="icon" color="#1989fa" />
        <span class="city">
          {{
          addressValue | formatCityName
          }}
        </span>
      </van-col>
      <van-col span="16" class="search">
        <van-search
          v-model="searchParams.keyword"
          :placeholder="`找${jobCategoryObj[jobTypeId]}--请输入搜索关键词`"
          @search="onSearch"
          background="#E6E6E6"
          shape="round"
        >  
        <template #action>
          <div @click="onSearch">搜索</div>
        </template>
      </van-search>
      </van-col>
      <van-col span="2" @click="showOverlay = true" class="others">
        <van-icon name="ellipsis" size="16" />
      </van-col>
    </van-row>

    <van-overlay :show="showOverlay" @click="showOverlay = false" class-name="over_layer">
      <van-cell-group class="layer">
        <van-cell value="扫一扫" />
      </van-cell-group>
    </van-overlay>

    <van-pull-refresh v-model="isRefreshing" @refresh="onRefresh">
      <van-swipe :autoplay="3000" class="my-swipe" indicator-color="white">
        <van-swipe-item v-for="(image, index) in images" :key="index">
          <van-image lazy-load :src="image" style="width: 100%;" @click="doCopy" />
        </van-swipe-item>
      </van-swipe>
      <com-filter-bar
        @clickFilter="clickFilter"
        @getFilterBarVal="getFilterBarVal"
        @getTreeData="getTreeData"
        :isDoFilter="isDoFilterAction"
      ></com-filter-bar>

      <div class="jobArr" v-if="jobList.length">
        <com-job-item
          v-for="(item, index) in jobList"
          :key="index"
          :jobItem="item"
          :keyWord="'home'"
        ></com-job-item>

        <com-pagination
          ref="comPagination_seekJob"
          :pageSizeCount="searchParams.pageSize"
          :total="total"
          @getPaginationValue="getPaginationValue_seekJob"
        ></com-pagination>

        <nut-backtop style="bottom: 62px"></nut-backtop>

        <van-divider :style="{color: '#747576', borderColor: '#747576', padding: '0 16px'}">我是有底线的</van-divider>
      </div>
    </van-pull-refresh>

    <com-filter-popup ref="comFilterPopupRef" @getFilterPopUpVal="toGetFilterPopUpVal"></com-filter-popup>
  </div>
</template>

<script>
import jobCategoryObj from '../../constants/jobCategoryObj'
import comJobItem from '../../components/comJobItem'
import comFilterBar from '../../components/comFilterBar'
import comFilterPopup from '../../components/comFilterPopup'
import comPagination from '../../components/comPagination'
import {cityFilter, concatIds, storageHistoryLocation} from '../../utils/index'
import constant from '../../utils/constant'
import {formatCityName} from '../../utils/format'

import banner_1 from '@/assets/img/home/banner_1.jpg'
import banner_2 from '@/assets/img/home/banner_2.jpg'
import banner_3 from '@/assets/img/home/banner_3.jpg'
import {mixin_one} from "../../mixin/mixin";

export default {
  name: 'seekJob',
  mixins: [mixin_one],
  components: {
    comJobItem,
    comFilterPopup,
    comFilterBar,
    comPagination
  },
  data() {
    return {
      jobCategoryObj,
      jobTypeId: '',
      getJobListtype: '', //我的公司进入
      jobList: [],
      images: [banner_1, banner_2, banner_3],
      showOverlay: false,
      isRefreshing: false,
      total: 0,
      cityName: '',
      streetName: '',
      addressValue: '',
      searchParams: {
        keyword: '', // 搜索关键字
        lng: null, // 经度
        lat: null, // 维度
        cityId: '', // 城市ID
        streetId: '', // 街道ID
        jobcategory: '', // 招聘类型(全职、兼职、小时工)
        orderItem: '', // 排序字段
        minSalary: null, // 起始薪资
        maxSalary: null, // 最大薪资
        nearby: '', // 附近地址
        classproperties: '', // 班制属性
        jobattributes: '', // 职位属性
        benefits: '', // 福利列表
        paymode: '', // 算薪方式
        payday: '', // 发薪日
        payMoneyDetailDate: '', // 发薪日详细日期

        createTime: '', // 发布时间
        pageIndex: 1, // 当前页
        pageSize: 10 // 每页显示条数
      } // 检索参数
    }
  },

  watch: {
    'searchParams.cityId': {
      handler: function (val) {
        if (this.getJobListtype) {
          return
        }
        let address = {
          type: '1', // 1为城市；2为街道
          id: this.searchParams.cityId,
          name: this.cityName
        }
        storageHistoryLocation(address)
      }
    },
    'searchParams.streetId': {
      handler: function (val) {
        if (this.getJobListtype) {
          return
        }
        let address = {
          type: '2', // 1为城市；2为街道
          id: this.searchParams.streetId,
          name: this.streetName
        }
        storageHistoryLocation(address)
      }
    },
    addressValue(val) {
      this.searchParams.pageIndex = 1
      this._getJobList()
    }
  },
  beforeRouteLeave(to, from, next) {
    // 从列表页去到别的页面，如果不是详情页，则不缓存列表页
    if (to.name !== 'jobDetail') {
      this.$route.meta.keepAlive = false
    } else {
      this.$route.meta.keepAlive = true
    }
    next()
  },
  mounted() {
    window.addEventListener('setItem', e => {
      if (e.key === constant.STORAGE_CURRENT_ADDRESS_VALUE) {
        this.handleCurrentAddress()
      }
    })
  },

  filters: {
    formatCityName(cityName) {
      return formatCityName(cityName)
    }
  },

  created() {
    if (this.$route.query.type) {
      this.getJobListtype = 'mycompany'
    }
    if (this.$route.query.id) {
      this.jobTypeId = this.$route.query.id
      this.searchParams.jobcategory = this.$route.query.id
    } else {
      this.$router.push('/')
    }

    // 如果当前选择了地址则使用选择地址，否则使用定位地址
    if (
      localStorage.getItem(constant.STORAGE_CURRENT_ADDRESS) &&
      localStorage.getItem(constant.STORAGE_CURRENT_ADDRESS_VALUE)
    ) {
      this.handleCurrentAddress()
    } else {
      // 配置地址: 一般在首页已经定位过了,这里直接取缓存里的地址,如果缓存中没有地址信息还需定位
      this.initLocation()
    }
  },

  methods: {
    /** 处理当前选择的位置 */
    handleCurrentAddress() {
      if (
        localStorage.getItem(constant.STORAGE_CURRENT_ADDRESS) &&
        localStorage.getItem(constant.STORAGE_CURRENT_ADDRESS_VALUE)
      ) {
        let address = JSON.parse(localStorage.getItem(constant.STORAGE_CURRENT_ADDRESS))
        if (address.type === '1') {
          // 1为城市；2为街道
          this.searchParams.cityId = address.id
          this.cityName = address.name
          this.searchParams.streetId = ''
          this.streetName = ''
        } else if (address.type === '2') {
          this.searchParams.cityId = ''
          this.cityName = ''
          this.searchParams.streetId = address.id
          this.streetName = address.name
        }
        this.searchParams.lat = localStorage.getItem(constant.STORAGE_CURRENT_LAT)
        this.searchParams.lng = localStorage.getItem(constant.STORAGE_CURRENT_LNG)
        this.addressValue = localStorage.getItem(constant.STORAGE_CURRENT_ADDRESS_VALUE)
      }
    },

    // 公共函数
    async _getJobList() {
      if (this.getJobListtype == 'mycompany') {
        this.searchParams.lat = ''
        this.searchParams.lng = ''
        this.searchParams.cityId = ''
        const res = await this.$api.job.getMycompanyJobPage(this.searchParams)
        if (res.code === 200) {
          this.jobList = res.data.items
          this.total = res.data.count
        }
      } else {
        const res = await this.$api.job.getJobPage(this.searchParams)
        if (res.code === 200) {
          this.jobList = res.data.items
          this.total = res.data.count
        }
      }
    },

    toGetFilterPopUpVal(val, val_2) {
      this.searchParams.classproperties = val.select_class_id // 班制：坐班、站班
      this.searchParams.jobattributes = val.select_position_attribute_id // 职位属性：两班倒、三班倒、、、
      this.searchParams.benefits = concatIds(val.select_welfare_list) // 福利列表
      this.searchParams.paymode = val.select_payWay_id // 算薪方式
      this.searchParams.payday = val.select_payMoneyDay_id // 发薪日
      this.searchParams.payMoneyDetailDate = val.select_payMoneyDay_detail // 发薪日详细日期
      this.searchParams.createTime = val.select_publish_date // 发布时间

      console.log('searchParams:', this.searchParams);

      this._updateFilterOperationObj(val_2);

      this.searchParams.pageIndex = 1
      this._getJobList()
    },

    getPaginationValue_seekJob(val) {
      // 指定页
      this.searchParams.pageIndex = val.pageIndex
      this._getJobList()
    },

    clickFilter() {
      // 通过props父组件的方法，可实现子组件向父组件中传值
      let filterPopupRef = this.$refs.comFilterPopupRef
      // 父组件调用子组件中的方法
      filterPopupRef.changeFilterPopupState()
    },
    getTreeData(val) {
      this.jobList = val
    },
    getFilterBarVal(val) {
      console.log('当前值---筛选条', val)

      this.searchParams.orderItem = val.order
      this.searchParams.nearby = val.nearby
      this.searchParams.minSalary = null
      this.searchParams.maxSalary = null
      if (val.salary) {
        // "salary_1": "2000以下",
        // "salary_2": "2000-4000",
        // "salary_3": "4000-6000",
        // "salary_4": "6000-8000",
        // "salary_5": "9000-10000",
        // "salary_6": "10000以上",
        switch (val.salary) {
          case 'salary_1':
            this.searchParams.maxSalary = 2000
            break
          case 'salary_2':
            this.searchParams.minSalary = 2000
            this.searchParams.maxSalary = 4000
            break
          case 'salary_3':
            this.searchParams.minSalary = 4000
            this.searchParams.maxSalary = 6000
            break
          case 'salary_4':
            this.searchParams.minSalary = 6000
            this.searchParams.maxSalary = 8000
            break
          case 'salary_5':
            this.searchParams.minSalary = 9000
            this.searchParams.maxSalary = 10000
            break
          case 'salary_6':
            this.searchParams.minSalary = 10000
        }
      }

      this.searchParams.pageIndex = 1
      this._getJobList()
    },

    onRefresh() {
      // 初始化页面： 将页面置为1。
      this.searchParams.pageIndex = 1
      this._getJobList()
      let comPagination_seekJob = this.$refs.comPagination_seekJob
      // 父组件调用子组件中的方法
      comPagination_seekJob.changePageIndex()
      this.isRefreshing = false
    },

    toJobDetailPage(id) {
      this.$router.push({
        path: `/jobDetail/${id}`
      })
    },

    doCopy: function () {
      this.$copyText(this.linkPhone).then(
        function (e) {
          Toast('复制成功, 将联系方式粘贴到手机电话即可联系，或粘贴添加微信。')
        },
        function (e) {
          Toast('复制出错')
        }
      )
    },

    /** 配置地址: 一般在首页已经定位过了,这里直接取缓存里的地址,如果缓存中没有地址信息还需定位  */
    initLocation() {
      let cityId = localStorage.getItem(constant.STORAGE_LOCATION_CITY_ID)

      let lng = localStorage.getItem(constant.STORAGE_LOCATION_LNG)

      let lat = localStorage.getItem(constant.STORAGE_LOCATION_LAT)

      let cityName = localStorage.getItem(constant.STORAGE_LOCATION_CITY_NAME)
      if (cityId && lng && lat && cityName) {
        // 直接配置缓存里的地址
        this.searchParams.cityId = cityId
        this.cityName = cityName
        this.searchParams.lng = lng
        this.searchParams.lat = lat
        this.addressValue = cityName

        let address = {
          type: '1', // 1为城市；2为街道
          id: cityId,
          name: cityName
        }
        this.$addStorageEvent(1, constant.STORAGE_CURRENT_ADDRESS, JSON.stringify(address))
        this.$addStorageEvent(1, constant.STORAGE_CURRENT_LAT, lat)
        this.$addStorageEvent(1, constant.STORAGE_CURRENT_LNG, lng)
        this.$addStorageEvent(1, constant.STORAGE_CURRENT_ADDRESS_VALUE, cityName)
      } else {
        // 还需要定位
        // 先使用ip定位（只能定位到地区范围，精度低但速度快）
        this.getLngLatLocation()
        // 高精确定位（精度高但速度慢）
        this.getLocation()
      }
    },

    /**
     * 高精确定位（精度高但速度慢）
     */
    getLocation() {
      const self = this
      AMap.plugin('AMap.Geolocation', function () {
        let geolocation = new AMap.Geolocation({
          // 是否使用高精度定位，默认：true
          enableHighAccuracy: true,
          // 设置定位超时时间，默认：无穷大
          timeout: 10000
        })

        geolocation.getCurrentPosition()
        AMap.event.addListener(geolocation, 'complete', onComplete)
        AMap.event.addListener(geolocation, 'error', onError)

        function onComplete(data) {
          // data是具体的定位信息
          console.log('APP定位成功信息：', data)
          if (data.status == 1) {
            let cityCode = data.addressComponent.citycode
            let city = cityFilter(cityCode)
            if (city) {
              self.$addStorageEvent(1, constant.STORAGE_LOCATION_CITY_ID, city.id)
              self.$addStorageEvent(1, constant.STORAGE_LOCATION_CITY_NAME, city.name)
              self.$addStorageEvent(1, constant.STORAGE_LOCATION_AD_CODE, data.addressComponent.adcode)
              self.$addStorageEvent(1, constant.STORAGE_LOCATION_TOWNSHIP, data.addressComponent.township)

              let address = {
                type: '1', // 1为城市；2为街道
                id: city.id,
                name: city.name
              }
              self.$addStorageEvent(1, constant.STORAGE_CURRENT_ADDRESS, JSON.stringify(address))
              self.$addStorageEvent(1, constant.STORAGE_CURRENT_LAT, data.position.lat)
              self.$addStorageEvent(1, constant.STORAGE_CURRENT_LNG, data.position.lng)
              self.$addStorageEvent(1, constant.STORAGE_CURRENT_ADDRESS_VALUE, city.name)
            }

            self.$addStorageEvent(1, constant.STORAGE_LOCATION_LAT, data.position.lat)
            self.$addStorageEvent(1, constant.STORAGE_LOCATION_LNG, data.position.lng)

            self.searchParams.pageIndex = 1
            self._getJobList()
          }
        }

        function onError(data) {
          // 定位出错
          console.log('APP定位失败错误：', data)
          // 调用ip定位
          // self.getLngLatLocation()
        }
      })
    },

    /** ip定位（只能定位到地区范围，精度低但速度快） */
    getLngLatLocation() {
      const self = this
      AMap.plugin('AMap.CitySearch', function () {
        let citySearch = new AMap.CitySearch()
        citySearch.getLocalCity(function (status, result) {
          if (status === 'complete' && result.info === 'OK') {
            // 查询成功，result即为当前所在城市信息
            console.log('APP通过ip获取当前城市：', result)
            //正向地理编码
            AMap.plugin('AMap.Geocoder', function () {
              let geocoder = new AMap.Geocoder({
                // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
                city: result.adcode
              })

              geocoder.getLocation(result.city, function (status, data) {
                if (status === 'complete' && data.info === 'OK') {
                  // result为对应的地理位置详细信息
                  console.log('APP通过ip获取当前地理位置', data)
                  let cityCode = data.geocodes[0].addressComponent.citycode
                  let city = cityFilter(cityCode)
                  if (city) {
                    self.$addStorageEvent(1, constant.STORAGE_LOCATION_CITY_ID, city.id)
                    self.$addStorageEvent(1, constant.STORAGE_LOCATION_CITY_NAME, city.name)
                    self.$addStorageEvent(1, constant.STORAGE_LOCATION_AD_CODE, result.adcode)
                    self.$addStorageEvent(1, constant.STORAGE_LOCATION_LNG, data.geocodes[0].location.lat)
                    self.$addStorageEvent(1, constant.STORAGE_LOCATION_LAT, data.geocodes[0].location.lng)
                    let address = {
                      type: '1', // 1为城市；2为街道
                      id: city.id,
                      name: city.name
                    }
                    self.$addStorageEvent(1, constant.STORAGE_CURRENT_ADDRESS, JSON.stringify(address))
                    self.$addStorageEvent(1, constant.STORAGE_CURRENT_LAT, data.geocodes[0].location.lat)
                    self.$addStorageEvent(1, constant.STORAGE_CURRENT_LNG, data.geocodes[0].location.lng)
                    self.$addStorageEvent(1, constant.STORAGE_CURRENT_ADDRESS_VALUE, city.name)
                  }

                  self.searchParams.pageIndex = 1
                  self._getJobList()
                }
              })
            })
          }
        })
      })
    },

    onSearch() {
      this.searchParams.pageIndex = 1
      this._getJobList()
    },

    /** 打开地址选择页 */
    toAddressPage() {
      this.$router.push({name: 'selectAddress', query: {pre: 'seekJob', jobTypeId: this.jobTypeId}})
    }
  }
}
</script>

<style lang="scss" scoped>
.page_seekJob {
  width: 100%;
  box-sizing: border-box;

  .title_home {
    height: 46px;
    line-height: 46px;
    text-align: center;
    background-color: #e6e6e6;
    color: #1989fa;
    .city_home {
      font-size: 14px;
      height: 34px;
      line-height: 34px;
      display: flex;
      justify-content: center;
      align-items: center;
      .icon {
        font-size: 19px;
      }
      .city {
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
    }
    .search {
      /deep/ .van-search {
        padding: 0;
      }
    }
  }
  .over_layer {
    margin-top: 46px;
    height: 100%;
    .layer {
      width: 30%;
      font-size: 14px;
      position: absolute;
      right: 0;
      z-index: 2;
    }
  }
  .my-swipe {
    width: 100%;
    height: 200px;
    overflow: hidden;
  }
}
</style>
